package com.kefu.boss.userdetails;

import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import com.google.common.collect.Sets;
import com.kefu.framework.config.KefuProperties;
import com.kefu.framework.config.KefuProperties.Client;

@Primary
@Component
@CacheConfig(cacheNames = "kefu_client_cache")
public class KefuClientDetailsService implements ClientDetailsService {
	@Autowired
	KefuProperties kefu;
	@Autowired
	ApplicationContext context;
	@Override
	@Cacheable
	public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
		BaseClientDetails details=new BaseClientDetails();
		details.setAccessTokenValiditySeconds(600);
		HashSet<String> resources=Sets.newHashSet(kefu.getSecurity().getBossClient().getResource());
		details.setResourceIds(resources);
		Client client=null;
		if(clientId.equals(kefu.getSecurity().getBossClient().getClientId())) {
			client=kefu.getSecurity().getBossClient();
		}

		if(client!=null) {
			String password=context.getBean(PasswordEncoder.class).encode(client.getClientSecret());
			details.setClientId(client.getClientId());
			details.setClientSecret(password);
			details.setScope(client.getScope());
			details.setAuthorizedGrantTypes(client.getGrantTypes());
			if(client.getTokenValiditySeconds()!=null) {
				details.setAccessTokenValiditySeconds(client.getTokenValiditySeconds());
			}
			if(client.getRefreshTokenValiditySeconds()!=null) {
				details.setRefreshTokenValiditySeconds(client.getRefreshTokenValiditySeconds());
			}
			return details;
		}
		return null;
	}

}
